import { defineStore } from "pinia";

import { NewsSummary } from "@/entity/NewsSummary";
import { fetchNewsSummary, fetchNewsContent } from "@/apis/NewsApi";

export const useNewsStore = defineStore("newsSummaryStore", {
  state: () => ({
    newsSummary: [] as NewsSummary[],
    refresh: false,
    newsContent: {} as { [key: string]: string },
  }),
  getters: {
    isDataStale: (state) => {
      return !state.newsSummary.length || state.refresh;
    },
  },
  actions: {
    async fetchSummary() {
      if (this.isDataStale) {
        this.refresh = false;
        this.newsSummary = await fetchNewsSummary();
      }
    },
    async refreshData() {
      this.refresh = true;
      await this.fetchSummary();
    },
    async fetchContent(id: string) {
      if (!this.newsContent[id]) {
        this.newsContent[id] = await fetchNewsContent(id);
      }
      return this.newsContent[id];
    },
  },
});
